# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2018/6/18 13:53
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : api.py
# @Software   : PyCharm
# -----------------------------------------
import json

from flask import Blueprint, request, jsonify

from .tools import create_db, show_users, show_databases, show_tables

info = Blueprint("info", __name__, url_prefix="/db/info")



@info.route("/create_database", methods=("POST",))
def create_database():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        conn = params["conn"]
        database = params["database"]
        infos = create_db(conn, database)
    except Exception as e:
        infos["msg"] = f"conn and database is needed! {e}"

    return jsonify(infos)



@info.route("/get_databases", methods=("POST", "GET"))
def get_databases():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        conn = params["conn"]
        infos = show_databases(conn)
    except Exception as e:
        infos["msg"] = f"conn is needed! {e}"
    return jsonify(infos)


@info.route("/get_database_tables", methods=("POST", "GET"))
def get_database_tables():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        conn = params["conn"]
        database = params["database"]
        infos = show_tables(conn, database)
    except Exception as e:
        infos["msg"] = f"conn and database is needed! {e}"

    return jsonify(infos)



@info.route("/get_users", methods=("POST", "GET"))
def get_users():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        conn = params["conn"]
        infos = show_users(conn)
    except Exception as e:
        infos["msg"] = f"conn is needed! {e}"

    return jsonify(infos)
